package com.jzg.jcptadmin.ui.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.method.NumberKeyListener;
import android.text.method.ReplacementTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.adpter.HistoryVinAdapter;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.ACache;
import com.jzg.jcptadmin.data.vo.VinDetails;
import com.jzg.jcptadmin.data.vo.Vindata;
import com.jzg.jcptadmin.presenter.QueryVinPresenter;
import com.jzg.jcptadmin.ui.VinResultActivity;
import com.jzg.jcptadmin.viewinterface.QueryVinFragmentInterface;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;

/**
 * Created by wangyd on 15/12/28.
 * Vin码查询
 */
public class QueryVinFragment extends Fragment implements View.OnClickListener, QueryVinFragmentInterface, AdapterView.OnItemClickListener {

    @Bind(R.id.vin_text)
    EditText vin_text;

    @Bind(R.id.query_btn)
    Button query_btn;

    @Bind(R.id.history_list)
    ListView history_list;

    @Bind(R.id.clear_btn)
    Button clear_btn;

    //当前历史记录
    private List<String> curHistoryVins;

    private AppContext appContext;

    private QueryVinPresenter queryVinPresenter;

    private HistoryVinAdapter historyVinAdapter;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        appContext = (AppContext) getActivity().getApplication();
        queryVinPresenter = new QueryVinPresenter(DataManager.getInstance(), appContext);
        queryVinPresenter.attachView(this);
        filterEditText();//过滤EditText
    }

    private void filterEditText() {
        vin_text.requestFocus();
        vin_text.setKeyListener(new NumberKeyListener() {
            @Override
            protected char[] getAcceptedChars() {
                // TODO Auto-generated method stub
                return new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
                        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
                        'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
                        'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
            }

            @Override
            public int getInputType() {
                // TODO Auto-generated method stub
                return 1;
            }
        });
        vin_text.setTransformationMethod(new InputLowerToUpper());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.query_vin_layout, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        showVinHistory();
    }

    @Override
    public void onPause() {
        super.onPause();
        queryVinPresenter.SaveList(curHistoryVins);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    @OnClick({R.id.query_btn, R.id.clear_btn})
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.query_btn:
                MobclickAgent.onEvent(getActivity(),"pinggushi_jishipingguchaxunvin");//友盟统计
                if (vin_text.getText().toString().trim().length() < 17) {
                    Toast.makeText(getActivity(), "VIN码长度不能小于17位", Toast.LENGTH_SHORT).show();
                    return;
                }
                ((BaseActivity) getActivity()).showDialog();
                queryVinPresenter.queryVin(appContext);
                break;
            case R.id.clear_btn:
                clearHistory();
                break;
        }
    }

    /**
     * 显示错误信息
     *
     * @param error 错误信息
     */
    @Override
    public void showError(String error) {
        ((BaseActivity) getActivity()).dismissDialog();
        Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
    }

    /**
     * 显示加载
     */
    @Override
    public void showDialog() {

    }

    /**
     * 关闭加载
     */
    @Override
    public void dismissDialog() {

    }

    /**
     * 清除历史记录
     */
    @Override
    public void clearHistory() {
        curHistoryVins.clear();
        queryVinPresenter.getVinHistory().clear();
        historyVinAdapter.notifyDataSetChanged();
        history_list.setVisibility(View.GONE);
        clear_btn.setVisibility(View.GONE);
        Vindata vindata = new Vindata();
        vindata.setShowVins(new ArrayList<String>());
        ACache.get(appContext).put("Vindata", vindata);
    }


    @Override
    public void showVinHistory() {
        //获取最终排序后的历史数据
        curHistoryVins = queryVinPresenter.sortVins(queryVinPresenter.getVinHistory());

        if (curHistoryVins.isEmpty()) {
            history_list.setVisibility(View.GONE);
            clear_btn.setVisibility(View.GONE);
        } else {
            history_list.setVisibility(View.VISIBLE);
            clear_btn.setVisibility(View.VISIBLE);
            historyVinAdapter = new HistoryVinAdapter(getActivity(), curHistoryVins);
            history_list.setAdapter(historyVinAdapter);
        }

    }


    /**
     * 跳转到VIN码查询结果
     *
     * @param vinDetails
     */
    @Override
    public void toVinResultActivity(VinDetails vinDetails) {
        ((BaseActivity) getActivity()).dismissDialog();
        if (vinDetails.getStatus() == 100) {

            ActivityHelp.startActivity(getActivity(), VinResultActivity.class, ActivityHelp.VINDETAILS, vinDetails);
        } else {
            Toast.makeText(getActivity(), vinDetails.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 获取vin查询请求需要的参数
     *
     * @return
     */
    @Override
    public Map<String, String> getQueryVinParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("op", "stylelist");
        params.put("vin", exChange(vin_text.getText().toString()));
//        params.put("vin", "Lfmape2c780037365");
        params.put("userId", String.valueOf(appContext.getUser().getUserId()));
//        params.put("userId", String.valueOf(5));
        return params;
    }

    /**
     * Callback method to be invoked when an item in this AdapterView has
     * been clicked.
     * <p>
     * Implementers can call getItemAtPosition(position) if they need
     * to access the data associated with the selected item.
     *
     * @param parent   The AdapterView where the click happened.
     * @param view     The view within the AdapterView that was clicked (this
     *                 will be a view provided by the adapter)
     * @param position The position of the view in the adapter.
     * @param id       The row id of the item that was clicked.
     */
    @OnItemClick({R.id.history_list})
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (R.id.history_list == parent.getId()) {
            if (curHistoryVins.size() > position) {
                String vin = curHistoryVins.get(position);
                vin_text.setText(vin);
            }
        }
    }

    public class InputLowerToUpper extends ReplacementTransformationMethod {
        @Override
        protected char[] getOriginal() {
            char[] lower = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
            return lower;
        }

        @Override
        protected char[] getReplacement() {
            char[] upper = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
            return upper;
        }

    }

    //小写转成大写
    public static String exChange(String str) {
        StringBuffer sb = new StringBuffer();
        if (str != null) {
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (Character.isUpperCase(c)) {
                    sb.append(c);
                } else if (Character.isLowerCase(c)) {
                    sb.append(Character.toUpperCase(c));
                } else {
                    sb.append(c);
                }
            }
        }

        return sb.toString();
    }
}